package com.ly.heart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.PageParam;
import com.ly.common.annotation.DataScope;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.CustomerVisitRecordEntity;
import com.ly.heart.domain.FileEntity;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.heart.mapper.CustomerVisitRecordMapper;
import com.ly.heart.service.IActModelService;
import com.ly.heart.service.ICustomerVisitRecordService;
import com.ly.heart.service.IFileInfoService;
import com.ly.heart.util.CurrentUserUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 客户拜访记录 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2024-09-29
 */
@Service
public class CustomerVisitRecordServiceImpl extends ServiceImpl<CustomerVisitRecordMapper, CustomerVisitRecordEntity> implements ICustomerVisitRecordService {

    @Resource
    private CustomerVisitRecordMapper customerVisitRecordMapper;
    @Resource
    private IActModelService iActModelService;
    @Resource
    private IFileInfoService iFileInfoService;

    @Override
    @DataScope ( deptAlias = "sd" )
    public AjaxResult list ( CustomerVisitRecordEntity customerVisitRecordEntity ) {
        customerVisitRecordEntity.setPage ( ( customerVisitRecordEntity.getPage () - 1 ) * customerVisitRecordEntity.getLimit () );
        List<CustomerVisitRecordEntity> customerVisitRecordEntities = customerVisitRecordMapper.selectCustomerVisitRecordEntityList ( customerVisitRecordEntity );
        customerVisitRecordEntities.forEach ( visit -> {
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId ( visit.getInstanceId () );
            Optional.ofNullable ( currentTaskVo ).ifPresent ( currentTask -> {
                visit.setCurrentTask ( currentTask );
            } );
        } );
        Integer count = customerVisitRecordMapper.selectCustomerVisitRecordEntityCount ( customerVisitRecordEntity );
        PageParam p = new PageParam ();
        p.setRecords ( customerVisitRecordEntities ).setTotal ( count );
        return AjaxResult.success ( p );
    }

    @Override
    public CustomerVisitRecordEntity querySingle ( String id ) {
        CustomerVisitRecordEntity customerVisitRecordEntity = customerVisitRecordMapper.selectCustomerVisitRecordEntityById ( id );
        List<FileEntity> list = iFileInfoService.list ( new LambdaQueryWrapper<FileEntity> ().eq ( FileEntity :: getRelationId, id ) );
        customerVisitRecordEntity.setFileEntities ( list );
        return customerVisitRecordEntity;
    }

    @Override
    public AjaxResult draft ( CustomerVisitRecordEntity customerVisitRecordEntity ) {
        customerVisitRecordEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ();
        customerVisitRecordEntity.setDocNo ( "KHBFJL".concat ( String.format ( "%08d", count ) ) );
        customerVisitRecordEntity.setDeptId ( CurrentUserUtil.getCompanyId () );
        customerVisitRecordEntity.setUserId ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        customerVisitRecordEntity.setCreateTime ( DateUtils.getNowDate () );
        customerVisitRecordEntity.setState ( ConstUtil.STATE_IN_DRAFT );
        updateFile ( customerVisitRecordEntity.getFileEntities (), customerVisitRecordEntity.getId () );
        boolean save = this.save ( customerVisitRecordEntity );
        if ( ! save ) {
            throw new CustomException ( "新增客户拜访记录失败！" );
        }
        return AjaxResult.success ( "暂存客户拜访记录成功", customerVisitRecordEntity.getId () );
    }

    @Override
    public AjaxResult submit ( CustomerVisitRecordEntity customerVisitRecordEntity ) {
        StartProcessDto startDto = new StartProcessDto ().
                setBusinessId ( customerVisitRecordEntity.getId () ).
                setBusinessType ( customerVisitRecordEntity.getBusinessType () ).setModelId ( customerVisitRecordEntity.getModelId () ).
                setBusinessName ( "客户拜访记录".concat ( customerVisitRecordEntity.getId () ) );
        String instanceId = iActModelService.startProcess ( startDto );
        boolean update = this.update ( new LambdaUpdateWrapper<CustomerVisitRecordEntity> ().
                set ( CustomerVisitRecordEntity :: getInstanceId, instanceId ).
                set ( CustomerVisitRecordEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                eq ( CustomerVisitRecordEntity :: getId, customerVisitRecordEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "提交客户拜访记录失败！" );
        }
        return AjaxResult.success ();
    }

    @Override
    public AjaxResult updateSingle ( CustomerVisitRecordEntity customerVisitRecordEntity ) {
        customerVisitRecordEntity.setUpdateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        customerVisitRecordEntity.setUpdateTime ( DateUtils.getNowDate () );
        updateFile ( customerVisitRecordEntity.getFileEntities (), customerVisitRecordEntity.getId () );
        boolean b = this.updateById ( customerVisitRecordEntity );
        if ( ! b ) {
            throw new CustomException ( "修改客户拜访记录失败！" );
        }
        return AjaxResult.success ();
    }

    @Override
    public AjaxResult deleteSingle ( String id ) {
        boolean update = this.update ( new LambdaUpdateWrapper<CustomerVisitRecordEntity> ().set ( CustomerVisitRecordEntity :: getIsUsed, ConstUtil.IS_USED_NO ).eq ( CustomerVisitRecordEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( "删除客户拜访记录失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 查询客户的回访记录
     * @param customerVisitRecordEntity
     * @return
     */
    @Override
    public List<CustomerVisitRecordEntity> queryList ( CustomerVisitRecordEntity customerVisitRecordEntity ) {
        List<CustomerVisitRecordEntity> customerVisitRecordEntities = customerVisitRecordMapper.queryList ( customerVisitRecordEntity );
        return customerVisitRecordEntities;
    }

    private void updateFile ( List<FileEntity> fileEntities, String relationId ) {
        if ( ! CollectionUtils.isEmpty ( fileEntities ) ) {
            iFileInfoService.remove ( new LambdaUpdateWrapper<FileEntity> ().eq ( FileEntity :: getRelationId, relationId ) );
            fileEntities.forEach ( file -> {
                file.setRelationId ( relationId );
                iFileInfoService.save ( file );
            } );
        }
    }

}
